package cn.zs.supply.common.core.web.filter;

import brave.Tracer;
import cn.zs.supply.common.constants.PubKeyDef;
import cn.zs.supply.common.core.context.RibbonFilterContextHolder;
import cn.zs.supply.common.core.web.UserSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @ClassName 链路追踪过滤器
 * @Description 实现TraceId、服务调用方、其他公共参数的透传
 * @Autor xiepengfei
 * @Data 2019/3/25 17:52
 **/
@Slf4j
public class TraceFilter implements Filter {
    private String serviceName = "";
    private Tracer tracer;

    public void setTracer(Tracer tracer) {
        this.tracer = tracer;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        serviceName = filterConfig.getInitParameter("serviceName");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        MDC.clear();
        try {
            UserSession.set(PubKeyDef.SESSION_USER_KEY, null);
        } catch (Exception ex) {
            log.error("清除ThreadLocal出错", ex);
        }
        String message = "";
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        String reqTarget = serviceName.substring(serviceName.lastIndexOf("-") + 1);

        //设置灰度标识
        String greyFlag = request.getHeader(PubKeyDef.GRAY_TAG);
        if (StringUtils.isNotBlank(greyFlag)) {
            RibbonFilterContextHolder.getCurrentContext().put(PubKeyDef.GRAY_TAG, greyFlag);
        }

        //设置traceId
        if (tracer != null) {
            String traceId = tracer.currentSpan().context().traceIdString();
            MDC.put(PubKeyDef.TRACE_ID, traceId);

            //修改tracer的HEADER_REQ_SOURCE
           // String reqSource = tracer.currentSpan().(PubKeyDef.LOG_REQ_SOURCE);
            tracer.currentSpan().tag(PubKeyDef.LOG_REQ_SOURCE, reqTarget);
        }
        //reqSource
        if (request.getHeader(PubKeyDef.HEADER_REQ_SOURCE) != null) {
            MDC.put(PubKeyDef.LOG_REQ_SOURCE, request.getHeader(PubKeyDef.HEADER_REQ_SOURCE));
        }
        //sequence
        if (request.getHeader(PubKeyDef.LOG_OUTER_SEQUENCE) != null) {
            String sequence = request.getHeader(PubKeyDef.LOG_OUTER_SEQUENCE);
            MDC.put(PubKeyDef.LOG_OUTER_SEQUENCE, sequence);
        }
        //reqTarget
        MDC.put(PubKeyDef.LOG_REQ_TARGER, reqTarget);
        log.info("请求URI:" + uri);
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
